#include "qmetronome.h"

void ERRCHECK(FMOD_RESULT result)
{
    if (result != FMOD_OK)
    {
        exit(-1);
    }
}

QMetronome::QMetronome(FMOD::System *sys)
{
	system=sys;
	system->createDSPByType(FMOD_DSP_TYPE_OSCILLATOR, &dsp);
	dsp->setParameter(FMOD_DSP_OSCILLATOR_RATE, 440.0f);
}

QMetronome::QMetronome(FMOD::System * sys,int bpm,int m1, int m2){
	system=sys;
	result=system->createDSPByType(FMOD_DSP_TYPE_OSCILLATOR, &dsp);
	result=dsp->setParameter(FMOD_DSP_OSCILLATOR_RATE, 440.0f);
	result=dsp->setParameter(FMOD_DSP_OSCILLATOR_TYPE, 4);
	result=dsp->setParameter(FMOD_DSP_OSCILLATOR_RATE, 1000.f);
	tempo=bpm;
	mesure1=m1;
	mesure2=m2;
	ttime=getTimeDuration();
}

QMetronome::~QMetronome(void)
{
}


void QMetronome::run(){
	while(1){
		for(int i=0;i<mesure1;i++){
				if(i==0){
					result=dsp->setParameter(FMOD_DSP_OSCILLATOR_RATE, 1000.f);
					result=system->playDSP(FMOD_CHANNEL_REUSE, dsp, true, &channel);
					result = dsp->setParameter(FMOD_DSP_OSCILLATOR_TYPE, 4);
					
				}
				else{
					result=dsp->setParameter(FMOD_DSP_OSCILLATOR_RATE, 550.0f);
					result = system->playDSP(FMOD_CHANNEL_REUSE, dsp, true, &channel);
                    result = dsp->setParameter(FMOD_DSP_OSCILLATOR_TYPE, 4);
                    
				}
				channel->setPaused(false);
				Sleep(((DWORD)((ttime)*1000)/2));
				channel->setPaused(true);
				Sleep(((DWORD)((ttime)*1000)/2));
		}
	}
}
void QMetronome::setMesure1(int m){
	mesure1=m;
	ttime=getTimeDuration();
}
void QMetronome::setMesure2(int m){
	mesure2=m;
	ttime=getTimeDuration();
}
void QMetronome::setTempo(int t){
	tempo=t;
	ttime=getTimeDuration();
}
double QMetronome::getTimeDuration(){

	return (((double)60/tempo)*mesure1)/mesure2;
}

FMOD::Channel *QMetronome::getChannel(){
	return channel;
}